package com.mchsdk.paysdk.activity.unity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.mchsdk.open.GPExitResult;
import com.mchsdk.open.GPUserResult;
import com.mchsdk.open.IGPExitObsv;
import com.mchsdk.open.IGPUserObsv;
import com.mchsdk.open.MCApiFactory;
import com.mchsdk.open.OrderInfo;
import com.mchsdk.open.PayCallback;
import com.mchsdk.open.UploadRoleCallBack;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zhujinzhujin
 * on 2017/1/23.
 */

public class UnityInterfaceActivity extends UnityPlayerActivity {

    private static final String TAG = "UnityInterfaceActivity";
    private String u3dOjectName;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        u3dOjectName = "";
    }

    public void initU3dParams(String objname, String paramsStr){
        if (TextUtils.isEmpty(objname)){
            Log.e(TAG, "objname is null");
            return;
        }
        u3dOjectName = objname;

        if (TextUtils.isEmpty(paramsStr)){
            Log.e(TAG, "paramsStr is null");
            return;
        }
        Log.w(TAG, "name:" + objname + ", params:" + paramsStr);
        JSONObject js = null;
        try {
            js = new JSONObject(paramsStr);
        } catch (JSONException e) {
            Log.e(TAG, "unity setParams" + e.toString());
            return;
        }

        MCApiFactory.getMCApi().setParams(js.optString("channel_id", ""),
                js.optString("channel_name", ""), js.optString("game_id", ""),
                js.optString("game_name", ""), js.optString("game_appid", ""),
                js.optString("paysdk_signkey", ""), js.optString("paysdk_address", ""));

        MCApiFactory.getMCApi().init(UnityInterfaceActivity.this, true);
    }

    public void startLogin(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            	//调用登录接口
                MCApiFactory.getMCApi().startlogin(UnityInterfaceActivity.this, new IGPUserObsv() {
                    @Override
                    public void onFinish(GPUserResult result) {
                        switch (result.getmErrCode()) {
                            case GPUserResult.USER_RESULT_LOGIN_FAIL:
                                Log.w(TAG, "登录失败");
//                                InvokeUnity("{\"rescode\":\"0\"}");
                                InvokeUnity("loginrescode=0");
                                break;
                            case GPUserResult.USER_RESULT_LOGIN_SUCC:
                                MCApiFactory.getMCApi().startFloating(UnityInterfaceActivity.this);

                                Log.w(TAG, "登录成功");
                                String uid = result.getAccountNo();// 登录用户id
                                String token = result.getToken();
//                                InvokeUnity("{\"rescode\":\"1\", " +
//                                        "\"userid\":\"" + uid +"\", " +
//                                        "\"token\":\"" + token+ "\"}");
                                InvokeUnity("loginrescode=1,userid=" + uid + ",token="+ token);
                                break;
                        }
                    }
                });
            }
        });
    }

    public void startPay(String goodsInfo){
        if (TextUtils.isEmpty(goodsInfo)){
            Log.e(TAG, "goodsInfo is null");
            InvokeUnity("payrescode=-100");
            return;
        }
        JSONObject js;
        try {
            js = new JSONObject(goodsInfo);
        } catch (JSONException e) {
            Log.e(TAG, "unity setParams" + e.toString());
            InvokeUnity("payrescode=-100");
            return;
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setProductName(js.optString("name", ""));// 物品名称
        orderInfo.setProductDesc(js.optString("desc", "")); // 物品描述
        orderInfo.setAmount(js.optInt("price", 0));//商品价格（单位分）
        orderInfo.setExtendInfo(js.optString("extend", ""));
        MCApiFactory.getMCApi().pay(UnityInterfaceActivity.this, orderInfo, new PayCallback() {
            @Override
            public void callback(String errorcode) {
                if(TextUtils.isEmpty(errorcode)){
                    return;
                }
//                InvokeUnity("{\"payrescode\":\"" + errorcode + "\"}");
                InvokeUnity("payrescode="+ errorcode);
            }
        });
    }
    
    public void uploadRoleInfo(String roleInfo){
    	if (TextUtils.isEmpty(roleInfo)){
            Log.e(TAG, "goodsInfo is null");
            InvokeUnity("uploadrolerescode=-200");
            return;
        }
        JSONObject js;
        try {
            js = new JSONObject(roleInfo);
        } catch (JSONException e) {
            Log.e(TAG, "unity setParams" + e.toString());
            InvokeUnity("uploadrolerescode=-200");
            return;
        }
        Log.e(TAG, "fun#uploadRoleInfo gameId:" + js.optString("gameId", "") + ", roleLevel:" + js.optString("roleLevel", ""));
    	MCApiFactory.getMCApi().uploadRole(UnityInterfaceActivity.this, 
    			js.optString("gameId", ""), 
    			js.optString("serverId", ""), js.optString("serverName", ""), 
    			js.optString("roleName", ""), js.optString("roleLevel", ""), 
    			new UploadRoleCallBack(){

					@Override
					public void onUploadComplete(String arg0) {
						InvokeUnity("uploadrolerescode=0");
					}});
    }
    
    public void logout(){
    	MCApiFactory.getMCApi().loginout(UnityInterfaceActivity.this);
    }
    
    public void exitToDesktop(){
    	 MCApiFactory.getMCApi().exitDialog(UnityInterfaceActivity.this, new IGPExitObsv(){

			@Override
			public void onExitFinish(GPExitResult exitResult) {
				switch (exitResult.mResultCode) {
                case GPExitResult.GPSDKExitResultCodeError:
                    Log.e(TAG, "退出回调:调用退出弹框失败");
                    break;
                case GPExitResult.GPSDKExitResultCodeExitGame:
                    Log.e(TAG, "退出回调:退出方法回调");
                    InvokeUnity("exitrescode=0");
                    // 关闭悬浮窗
                    MCApiFactory.getMCApi().stopFloating(UnityInterfaceActivity.this);
                    // 下面是退出逻辑,解决退出之后微信还在的问题
                    Intent MyIntent = new Intent(Intent.ACTION_MAIN);
                    MyIntent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(MyIntent);
                    break;
            }
				
			}});
    }

    public void startFloating(){
        MCApiFactory.getMCApi().startFloating(UnityInterfaceActivity.this);
    }
    
    public void stopFloating(){
        MCApiFactory.getMCApi().stopFloating(UnityInterfaceActivity.this);
    }

    /**
     * 回调unity方法
     * @param str 回传参数
     */
    public void InvokeUnity(String str){
        if (TextUtils.isEmpty(u3dOjectName)){
            Log.e(TAG, "未设置接收Unity广播的物体名称");
            return;
        }
        UnityPlayer.UnitySendMessage(u3dOjectName, "sdkResultListener", str);
    }


}
